<?php


namespace app\common\model;


use think\Model;

class Comment extends Model
{
    protected $name = 'comment';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'create_time';
    protected $updateTime = false;

    protected $append = ['create_time_text'];
    /*    public function child()
        { 目标
            return $this->hasMany(get_class($this), 'pid', 'id');
        }

        public function children()
        {
            return $this->child()->with('child');
        }*/

    //
    public function comments()
    {
        return $this->hasMany(Comment::class, 'pid', 'id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id')->field('id,nick_name,avatar');
    }

    public function repleyuser()
    {
        return $this->belongsTo(User::class, 'reply_user_id', 'id')->field('id,nick_name,avatar');;
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: $data['create_time'] ?: null;
        return format_date($value);
    }

    public function getContentAttr($value, $data)
    {
        $value = $value ?? $data['content'] ?: '';
        return html_entity_decode($value);
    }


    public static function getCommentList(
        $page = 1,
        $limit = 10,
        $where = [],
        $with = [],
        $field = '*',
        $order = 'create_time desc'
    )
    {
        $count = self::where($where)
            ->with($with)
            ->order($order)
            ->count();
        $list = self::where($where)
            ->with($with)
            ->field($field)
            ->page($page, $limit)
            ->withCount(['comments'])
            ->order($order)
            ->select();
        return [$count, $list];
    }

}
